home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / utility.lha / utility / pool.C < prev    next >
C/C++ Source or Header  |  1993-08-08  |  1KB  |  62 lines

  1. // $Id: pool.C,v 1.3 91/09/06 17:04:25 dag Exp $
  2. //
  3. // Author:
  4. //
  5. // Dag Bruck, Department of Automatic Control, Lund Institute of Technology,
  6. // Box 118, S-221 00 Lund, Sweden (dag@control.lth.se).
  7.  
  8.  
  9. #include <pool.H>
  10.  
  11.  
  12. const unsigned UNIT = sizeof(Pool :: Pool_Element);
  13.  
  14.  
  15. Pool :: Pool(unsigned n)
  16.     : free_list(0), blockp(0), sz(((n + UNIT - 1) / UNIT) * UNIT)
  17. {
  18.   alloc_block();
  19. }
  20.  
  21.  
  22. Pool :: ~Pool()
  23. {
  24.   register Pool_Block* b;
  25.  
  26.   while (blockp != 0) {
  27.     b = blockp->next;
  28.     delete blockp;
  29.     blockp = b;
  30.   }
  31. }
  32.  
  33.  
  34. void Pool :: alloc_block()
  35. {
  36.   register unsigned n = (UNIT*1024) / sz;
  37.   // The number of elements to allocate in a block
  38.  
  39.   // Allocate a new block of elements, and insert it into a list
  40.   // so it can be released when the pool is destroyed.
  41.   
  42.   register Pool_Block* blk =
  43.     (Pool_Block *) new char[sizeof(Pool_Block) + n * sz];
  44.   blk->next = blockp;
  45.   blockp = blk;
  46.  
  47.   // Link together all elements in the new block.
  48.   
  49.   register Pool_Element* pe = &blk->pe;
  50.   while (--n > 0) {
  51.     pe->next = (Pool_Element *) ((char *) pe + sz);
  52.     pe = pe->next;
  53.   }
  54.  
  55.   // The last element of the block points to the existing free list,
  56.   // which normally is empty (but needn't be).  The new free list
  57.   // starts with the first element of the newly allocated block.
  58.  
  59.   pe->next = free_list;
  60.   free_list = &blk->pe;
  61. }
  62.